package com.example.service.impl;

import com.example.entity.MessageNotice;
import com.example.entity.authority.*;
import com.example.entity.paperlessMaintance.PaperlessMaintanceApply;
import com.example.entity.training.TrainingPlan;
import com.example.ext.entity.ExtSysUser;
import com.example.mapp.*;
import com.example.service.PaperlessMaintService;
import com.example.util.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PaperlessMaintServiceImpl implements PaperlessMaintService {

    private static final Logger logger = LoggerFactory.getLogger(PaperlessMaintServiceImpl.class);
    @Autowired
    PaperlessMaintMapp paperlessMaintMapp;

    @Autowired
    private PartyMapp partyMapp;

    @Autowired
    private MessageNoticeMapp messageNoticeMapp;

    @Autowired
    private SysUserMapp userMapp;

    @Autowired
    private PartyCheckMapp partyCheckMapp;

    @Autowired
    private Environment environment;

    @Autowired
    private PartyUserMapp partyUserMapp;

    @Autowired
    private SysUserRoleMapp sysUserRoleMapp;




    @Override
    public Map<String, Object> query(PaperlessMaintanceApply paperlessMaintanceApply) {
        Map<String,Object> resultMap = new HashMap<>();
        try{
            if((paperlessMaintanceApply.getCurrentPage()) != null && paperlessMaintanceApply.getPageSize() != null){
                Page<TrainingPlan> page = PageHelper.startPage(paperlessMaintanceApply.getCurrentPage(),paperlessMaintanceApply.getPageSize());
                List<PaperlessMaintanceApply> list = paperlessMaintMapp.query(paperlessMaintanceApply);
                resultMap.put("list",list);
                resultMap.put("total",page.getTotal());
            }else{
                List<PaperlessMaintanceApply> list = paperlessMaintMapp.query(paperlessMaintanceApply);
                resultMap.put("list",list);
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",resultMap);
    }

    @Override
    @Transactional
    public Map<String, Object> add(PaperlessMaintanceApply paperlessApply) {
        try{

            /**
             * 新增前需要先校验。
             */
            paperlessApply.setUserCode(paperlessApply.getUserCode().trim());
            paperlessApply.setPartyName(paperlessApply.getPartyName().trim());

            SystemUser systemUser = userMapp.findUserPartyByUserCode(paperlessApply.getUserCode());
            if(systemUser!=null){
                return ResultUtil.returnError("用户名:"+paperlessApply.getUserCode()+" 已存在！",null);
            }
            //查询企业是否注册
            PartyCheck partyCheck1 = partyCheckMapp.queryByPartyName(paperlessApply.getPartyName());
            if(partyCheck1!=null && partyCheck1.getStatus().equals("2")){
                return ResultUtil.returnError("单位:"+paperlessApply.getPartyName()+" 已申请过注册，且已审批通过！",null);
            }

            PaperlessMaintanceApply param = new PaperlessMaintanceApply();
            param.setPartyName(paperlessApply.getPartyName());
            //查询无纸化是否注册过
            List<PaperlessMaintanceApply> maintanceApplies = paperlessMaintMapp.query(param);
            if(!CollectionUtils.isEmpty(maintanceApplies) && "2".equals(maintanceApplies.get(0).getApplyStatus())){
                return ResultUtil.returnError("单位:"+paperlessApply.getPartyName()+" 已申请过无纸化维保，且已审批通过！",null);
            }

            if(paperlessApply.getBusinessLicenseImg() != null && !"".equals(paperlessApply.getBusinessLicenseImg())
                && !"null".equals(paperlessApply.getBusinessLicenseImg())){
                //通用文字识别营业执照，与填写项进行比较
                Map resmap = AipUtil.checkBussinessImg(environment.getProperty("upload",String.class)+paperlessApply.getBusinessLicenseImg(),
                        paperlessApply.getPartyName(),paperlessApply.getCorporation(),paperlessApply.getCreditCode());
                if(resmap!=null){
                    boolean hasPartyName = Boolean.parseBoolean(resmap.get("hasPartyName")+"");
                    boolean hasCorporation = Boolean.parseBoolean(resmap.get("hasCorporation")+"");
                    boolean hasCreditCode = Boolean.parseBoolean(resmap.get("hasCreditCode")+"");
                    String errorMessage = "";
                    if(!hasPartyName){
                        errorMessage += "公司名称与营业执照中的不一致。";
                    }
                    if(!hasCorporation){
                        errorMessage += "法人名字与营业执照中的不一致。";
                    }
                    if(!hasCreditCode){
                        errorMessage += "信用代码与营业执照中的不一致。";
                    }
                    if(errorMessage.length()>0){
                        return ResultUtil.returnError(errorMessage,null);
                    }

                }else{
                    return ResultUtil.returnError("请上传清晰完整的营业执照照片",null);
                }
            }

            paperlessApply.setApplyStatus("1");
            paperlessApply.setApplyDate(DateUtils.getDate("yyyy-MM-dd"));
            paperlessMaintMapp.insert(paperlessApply);


            /**
             * 给监管部门发送通知，让其及时审批
             */
            Map<String, Object> map = new HashMap<>();
            map.put("roleName", "%管理人员%");
            map.put("partyId", paperlessApply.getJgPartyId());
            List<String> users = partyMapp.queryUserList(map);

            for (String userId : users) {
                String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                MessageNotice msg = new MessageNotice();
                msg.setTitle("无纸化维保申请");
                msg.setContent("您有一份无纸化维保申请，需要您审批，请及时确认处理！");
                msg.setReceiveUserId(userId);
                msg.setIsRead("0");
                msg.setNoticeTime(noticeTime);
                msg.setReceivePartyId(paperlessApply.getJgPartyId());
                messageNoticeMapp.add(msg);
            }
            return ResultUtil.returnSuccess("无纸化维保申请成功，等待监管部门审批", null);
        }catch (Exception e){
            logger.error("无纸化维保申请记录添加失败！",e);
            return ResultUtil.returnError("新增失败",null);
        }
    }

    /**
     * 对无纸化维保申请进行审批
     * @param paperlessApply
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> update(PaperlessMaintanceApply paperlessApply) {
        try {
            //查询用户是否存在
            PaperlessMaintanceApply paperlessApply1 = paperlessMaintMapp.queryById(paperlessApply.getId().toString());
            if(paperlessApply1 == null){
                return ResultUtil.returnError("用户:"+paperlessApply.getUserCode()+" 不存在！",null);
            }
            //审核通过才记录到系统中
            if("2".equals(paperlessApply.getApplyStatus())) {
                //用户名密码添加到用户登陆表（sys_user）其他信息添加到用户表user
                ExtSysUser sysUser = new ExtSysUser();
                //企业用户
                sysUser.setUserCode(paperlessApply.getUserCode());
                sysUser.setPassword(paperlessApply.getPassword());
                sysUser.setUserName(paperlessApply.getUserCode());
                sysUser.setType("party");
                sysUser.setUserState("1");
                userMapp.add(sysUser);
                Party party = new Party();
                BeanCopUtil.converJavaBean(party, paperlessApply);
                party.setParentId(paperlessApply.getJgPartyId());
                Party party1 = partyMapp.queryByName(party.getPartyName());
                //如果是导入的就更新
                if (party1 != null) {
                    party.setId(party1.getId());
                    party.setParentId(party1.getParentId());
                    partyMapp.update(party);
                } else {
                    partyMapp.insert(party);
                }

                //设置用户和机构的关联关系
                PartyUser partyUser = new PartyUser();
                partyUser.setPartyId(party.getId() + "");
                partyUser.setUserId(sysUser.getId() + "");
                partyUserMapp.insert(partyUser);
                //添加角色1默认是管理员
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(Integer.parseInt(sysUser.getId().toString()));
                //设置为管理员
                if ("1".equals(party.getPartyType())) {
                    sysUserRole.setRoleId(14);
                } else if ("2".equals(party.getPartyType())) {
                    sysUserRole.setRoleId(13);
                } else if ("3".equals(party.getPartyType())) {
                    sysUserRole.setRoleId(15);
                }

                sysUserRoleMapp.insert(sysUserRole);
            }
            //更新 申请记录的状态
            paperlessApply.setApprovalDate(DateUtils.getDate("yyyy-MM-dd"));
            paperlessMaintMapp.update(paperlessApply);
            try {
                //发送邮件
                String hostName = environment.getProperty("email.hostName", String.class);
                Integer port = environment.getProperty("email.port", Integer.class);
                String form = environment.getProperty("email.form", String.class);
                String password = environment.getProperty("email.password", String.class);
                String to = paperlessApply.getContactsEmile();
                String status = "";
                if ("1".equals(paperlessApply.getApplyStatus())) {
                    status = "申请中。";
                }
                if ("2".equals(paperlessApply.getApplyStatus())) {
                    status = "通过。您的账号是：" + paperlessApply.getUserCode() + " 密码是：" + paperlessApply.getPassword() + "。";
                }
                if ("3".equals(paperlessApply.getApplyStatus())) {
                    status = "拒绝。原因是：" + paperlessApply.getRemarks();
                }
                String msg = paperlessApply.getPartyName() + "您好，您的审核结果是：" + status + "";
                EmailUtil.sendEmail(hostName, port, form, to, "无纸化维保审核结果", msg, password);
            } catch (Exception e) {
                logger.error("发邮件失败" + e.getMessage(), e);
            }

        }catch (Exception e){
            logger.error("审核企业注册 失败"+e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.returnError("注册失败，系统异常",null);
        }
        return ResultUtil.returnSuccess("注册成功",null);
    }
}
